import unittest

from NoSQL4Cassandra.src.cassandra_connect import CassandraConnect


class CassandraConnectTest(unittest.TestCase):
    cc = None

    @classmethod
    def setUpClass(cls) -> None:
        cls.cc = CassandraConnect()

    @classmethod
    def tearDownClass(cls) -> None:
        cls.cc.close()

    def test_0_create_keyspace(self):
        """测试创建keyspace"""
        self.cc.create_keyspace("test")
        self.assertTrue("test" in self.cc.cluster.metadata.keyspaces)

    def test_1_create_table(self):
        """测试创建表"""
        self.cc.create_table("test", "test", [["name", "varchar primary key"], ["age", "int"]])
        self.assertTrue("test" in self.cc.cluster.metadata.keyspaces["test"].tables)

    def test_2_insert_one(self):
        """测试插入值"""
        self.cc.insert_one("test", "test", ["name", "age"], ["test", 10])
        result = self.cc.query("test", "test", "*", "name='test'")
        self.assertTrue(result.one().name == "test" and result.one().age == 10)

    def test_3_insert_many(self):
        """测试批量插入值"""
        values = [["test1", 10], ["test2", 10]]
        self.cc.insert_many("test", "test", ["name", "age"], values)
        for value in values:
            where_condition = "name='{0}'".format(value[0])
            result = self.cc.query("test", "test", "*", where_condition)
            self.assertTrue(result.one().name == value[0] and result.one().age == value[1])

    def test_4_query(self):
        """测试查询值"""
        verification_result = ["test", "test1", "test2"]
        results = self.cc.query("test", "test", "*", "age=10")
        for result in results:
            self.assertTrue(result.name in verification_result)

    def test_5_update(self):
        """测试更新值"""
        self.cc.update("test", "test", ["age"], [20], "name='test'")
        result = self.cc.query("test", "test", "*", "name='test'")
        self.assertTrue(result.one().age == 20)

    def test_6_delete(self):
        """测试删除值"""
        self.cc.delete("test", "test", "name='test'")
        result = self.cc.query("test", "test", "*", "name='test'")
        self.assertTrue(result.one() is None)

    def test_7_delete_table(self):
        """测试删除table"""
        self.cc.delete_table("test", "test")
        self.assertTrue("test" not in self.cc.cluster.metadata.keyspaces["test"].tables)

    def test_8_delete_keyspace(self):
        """测试删除keyspace"""
        self.cc.delete_keyspace("test")
        self.assertTrue("test" not in self.cc.cluster.metadata.keyspaces)


if __name__ == '__main__':
    unittest.main()